import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';

class Routers {
  //路由管理
  static final FluroRouter router = FluroRouter();

  //注册路由表
  static void configureRoutes(List<RouterItem> routerItemList) {
    router.notFoundHandler = Handler(
      handlerFunc: (context, parameters) {
        print('router not found!');
        return null;
      },
    );
    for (var element in routerItemList) {
      router.define(element.path, handler: element.handler);
    }
  }

  //跳转到页面
  static navigateTo(BuildContext context, String path,
      {Map<String, dynamic>? params,
      bool replace = false, //是否替代当前的page
      bool clearStack = false, // 是否销毁当前的Page
      TransitionType transition = TransitionType.fadeIn}) {
    FocusScope.of(context).requestFocus(FocusNode()); //获取页面焦点
    String query = "";
    if (params != null) {
      int index = 0;
      for (var key in params.keys) {
        var value = Uri.encodeComponent(params[key]);
        if (index == 0) {
          query = "?";
        } else {
          query = "$query&";
        }
        query += "$key=$value";
        index++;
      }
    }
    print('我是navigateTo传递的参数：$query');
    path = path + query;
    router.navigateTo(context, path,
        replace: replace, clearStack: clearStack, transition: transition);
  }

  ///获取跳转的结果（成功、失败信息）不常用
  static navigateToForResult(
      BuildContext context, String path, Function(Object) fun,
      {Map<String, dynamic>? params,
      bool replace = false, //是否替代当前的page
      bool clearStack = false, // 是否销毁当前的Page
      TransitionType transition = TransitionType.fadeIn}) {
    FocusScope.of(context).requestFocus(FocusNode()); //获取页面焦点
    String query = "";
    if (params != null) {
      int index = 0;
      for (var key in params.keys) {
        var value = Uri.encodeComponent(params[key]);
        if (index == 0) {
          query = "?";
        } else {
          query = "$query&";
        }
        query += "$key=$value";
        index++;
      }
    }
    path = path + query;
    router
        .navigateTo(context, path,
            replace: replace, clearStack: clearStack, transition: transition)
        .then((value) {
      if (value == null) {
        return;
      }
      fun(value);
    }).catchError((error) {
      print(error);
    });
  }

  //返回上一级页面
  static void goBack(BuildContext context) {
    //获取页面焦点
    FocusScope.of(context).requestFocus(FocusNode());
    Navigator.pop(context);
  }

  //带参数返回
  static void goBackWithParams(BuildContext context, result) {
    FocusScope.of(context).requestFocus(FocusNode());
    Navigator.pop(context, result);
  }
}

///路由对象
class RouterItem {
  RouterItem(this.path, this.handler, {this.name});

  //页面名称
  String? name;
  //路由地址
  String path;
  //路由handler
  Handler handler;
}
